package com.android.pinlingqian.view.group;


import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.pinlingqian.MainActivity;
import com.android.pinlingqian.R;
import com.android.pinlingqian.activity.BaseObject;
import com.android.pinlingqian.activity.CityChoose;
import com.android.pinlingqian.activity.GoodsStoreActivity;
import com.android.pinlingqian.activity.MainRecommendType;
import com.android.pinlingqian.activity.MainTab;
import com.android.pinlingqian.activity.mine.LoginActivity;
import com.android.pinlingqian.model.group.CitySetData;
import com.android.pinlingqian.model.group.CitySetDataCallback;
import com.android.pinlingqian.utils.ConstantsUrl;
import com.android.pinlingqian.utils.HttpUtils;
import com.android.pinlingqian.utils.LoginState;
import com.android.pinlingqian.utils.MyLog;
import com.android.pinlingqian.utils.ObjectUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

import static com.tencent.open.utils.Global.getSharedPreferences;


public class BannerItemFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private String mParam1;
    private int mParam2;
    private String mParam3;
    private View view;
    private LocationClient mLocationClient;
    private LocationClientOption option = new LocationClientOption();
    private MyLocationListener myLocationListener= new MyLocationListener();
    private String locationcity;
    private String returncity;
    private List<String> permissionList;
    private boolean islocation=false;
    private FragmentActivity mcontext;
    public static BannerItemFragment newInstance(String thumb, int photolength, String link) {
        BannerItemFragment fragment = new BannerItemFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, thumb);
        args.putInt(ARG_PARAM2, photolength);
        args.putString(ARG_PARAM3, link);
        fragment.setArguments(args);
        return fragment;
    }

    public BannerItemFragment() {

    }
    //同城商品定位逻辑
    private void requestLocation()
    {
        islocation=true;
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        //option.setScanSpan(3000);
        mLocationClient.setLocOption(option);
        if(islocation) {
            mLocationClient.start();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestcode,String[] permissions,int[] grantResults)
    {
        switch (requestcode)
        {
            case 1:
                if(grantResults.length>0)
                {
                    for(int result:grantResults)
                    {
                        if(result!= PackageManager.PERMISSION_GRANTED)
                        {
                            Toast.makeText(getActivity(),"尚不能应用定位",Toast.LENGTH_LONG).show();
                            int requestCode =1;
                            startActivityForResult(new Intent(mcontext, CityChoose.class),requestCode);
                            return;
                        }
                    }
                    requestLocation();
                }
                else
                {
                    int requestCode =1;
                    startActivityForResult(new Intent(mcontext, CityChoose.class),requestCode);
                    Toast.makeText(getActivity(),"发生未知错误",Toast.LENGTH_LONG).show();
                }
                break;
            default:break;
        }
    }
    public class  MyLocationListener implements BDLocationListener
    {
        @Override
        public void onReceiveLocation(BDLocation location)
        {
            locationcity =location.getCity();
            PostCitySet();
        }
        @Override
        public void onConnectHotSpotMessage(String var1, int var2)
        {

        }
    }
    private void PostCitySet()
    {
        String address = ConstantsUrl.domain + ConstantsUrl.CITYLOCATE;
        String getid = LoginState.getInstance().getid(mcontext);
        String getpd = LoginState.getInstance().getpd(mcontext);
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("UPSW", getpd);
        map.put("city",locationcity);
        HttpUtils.post(address,header, map, new CitySetDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                int requestCode =1;
                startActivityForResult(new Intent(mcontext, CityChoose.class),requestCode);
            }

            @Override
            public void onResponse(CitySetData response, int id) {
                if (response.getCode() == 0) {
                    String zone = response.getData().getZone();
                    returncity = response.getData().getCity();
                    SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
                    if(sp!=null) {
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString(ConstantsUrl.USERDATA_ZONE, zone);
                        edit.putString(ConstantsUrl.USERDATA_CITY, returncity);
                        edit.commit();
                    }
                    Intent intent_sc = new Intent(mcontext, BaseObject.class);
                    intent_sc.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"同城商品");
                } else {
                    int requestCode =1;
                    startActivityForResult(new Intent(mcontext, CityChoose.class),requestCode);
                }

            }
        });
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getInt(ARG_PARAM2);
            mParam3 = getArguments().getString(ARG_PARAM3);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
        }
         view = inflater.inflate(R.layout.item_fragment_banner, null);
        mcontext = getActivity();
        ImageView iv = (ImageView) view.findViewById(R.id.imageView1);
        ObjectUtils.photo2(getActivity(), mParam1, iv);
        iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String id="";
                String title = "";
                MyLog.e("iiddddsssd",mParam3);
                if(mParam3!=null) {
                    if (mParam3.contains(":")) {
                        int index = mParam3.indexOf(":");
                        int length = mParam3.length();
                        title = mParam3.substring(0, index - 1);
                        id = mParam3.substring(index, length - 1);
                        MyLog.e("iiddddd", id);
                        MyLog.e("ttitle", title);
                    } else {
                        title = mParam3;
                    }
                    switch (title) {
                        case "Seckill":
                            Intent intent = new Intent(getActivity(), MainTab.class);
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 0);
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 9);
                            startActivity(intent);
                            break;
                        case "FreeTest":
                            Intent intent1 = new Intent(getActivity(), MainRecommendType.class);
                            intent1.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE, "免费试用");
                            startActivity(intent1);
                            break;
                        case "BrandDiscount":
                            Intent intent2 = new Intent(getActivity(), MainRecommendType.class);
                            intent2.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE, "品牌折扣");
                            startActivity(intent2);
                            break;
                        case " Spread":
                            Intent intent_tabs = new Intent(getActivity(), MainTab.class);
                            intent_tabs.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 0);
                            intent_tabs.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 8);
                            startActivity(intent_tabs);
                            break;
                        case "FreePostage":
                            Intent intent3 = new Intent(getActivity(), MainRecommendType.class);
                            intent3.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE, "9.9元包邮");
                            startActivity(intent3);
                            break;
                        case "HotSail":
                            Intent intenthot = new Intent(getActivity(), BaseObject.class);
                            intenthot.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "热搜");
                            startActivity(intenthot);
                            break;
                        case "Neighbor":
                            Intent intent4 = new Intent(getActivity(), MainRecommendType.class);
                            intent4.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE, "邻居团");
                            startActivity(intent4);
                            break;
                        case "Promote":
                            Intent intent5 = new Intent(getActivity(), MainRecommendType.class);
                            intent5.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE, "推广团");
                            startActivity(intent5);
                            break;
                        case "NewHotSail":
                            MainActivity A = (MainActivity) getActivity();
                            A.ChangeMainFragment(1);
                            break;
                        case "SameCity":
                            FragmentActivity mcontext = getActivity();
                            if (LoginState.getInstance().isLogin(mcontext)) {
                                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                    permissionList.clear();
                                    permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
                                }
                                String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
                                MyLog.e("oonzone1", zone);
                                if (zone.equals("") || zone == null) {

                                    if (!permissionList.isEmpty()) {
                                        String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                                        ActivityCompat.requestPermissions(getActivity(), permissions, 1);
                                    } else {
                                        requestLocation();
                                    }

                                } else {
                                    Intent intent_sc = new Intent(mcontext, BaseObject.class);
                                    intent_sc.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "同城商品");
                                    startActivity(intent_sc);
                                }
                            } else {

                                int requestCode = 2;
                                startActivityForResult(new Intent(mcontext, LoginActivity.class), requestCode);
                            }
                            break;
                        case "Stair":
                            Intent intentthemetic = new Intent(getActivity(), BaseObject.class);
                            intentthemetic.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, id);
                            startActivity(intentthemetic);
                            break;
                        case "Store":
                            Intent intent6 = new Intent(getActivity(), GoodsStoreActivity.class);
                            intent6.putExtra("storeid", id);
                            startActivity(intent6);
                            break;
                        case "Detail":
                            ObjectUtils.ToDetailActivity(getActivity(), 1, id, "");
                            break;
                        case "GoodsList":
                            Intent intentList = new Intent(getActivity(), BaseObject.class);
                            intentList.putExtra("top", id);
                            startActivity(intentList);
                            break;
                    }
                }
//                Intent intent = new Intent(getActivity(), BaseObject.class);
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "");
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, mParam3);
//                startActivity(intent);
            }
        });

        return view;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode)
        {
            case 1:
                String zone1 = LoginState.getInstance().getUserInfo(mcontext, 2);
                if(zone1.equals("")||zone1==null) {
                    requestLocation();
                }
                else
                {
                    Intent intent_sc = new Intent(mcontext, BaseObject.class);
                    intent_sc.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"同城商品");
                    startActivity(intent_sc);
                }
                break;
            case 2:
                if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
                {
                    permissionList.clear();
                    permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
                MyLog.e("oonzone",zone);
                MyLog.e("oonzone1","oonzone1");
                if(zone.equals("")||zone==null) {
                    if(!permissionList.isEmpty())
                    {
                        String [] permissions = permissionList.toArray(new String[permissionList.size()]);
                        ActivityCompat.requestPermissions(getActivity(),permissions,1);
                    }
                    else
                    {
                        requestLocation();
                    }

                }
                else
                {
                    Intent intent_sc = new Intent(mcontext, BaseObject.class);
                    intent_sc.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"同城商品");
                    startActivity(intent_sc);
                }
                break;

        }
    }


}
